﻿using System;
using System.Web;
using Yule8xCommon.Typelib;
using System.Web.Security;

namespace Yule8xCommon.Applib
{
    public class WechatUtil
    {
        /// <summary>
        /// 获取基础token（有效期7200秒，开发者必须在自己的服务全局缓存token）
        /// </summary>
        /// <returns></returns>
        public static string GetToken()
        {
            HttpApplicationState application = HttpContext.Current.Application;
            object token = application.Get("token");
            if (null != token)
            {
                WxTokenObject curtoken = token as WxTokenObject;
                if (null != curtoken && curtoken.expires_time >= DateTime.Now)
                {
                    return curtoken.access_token;
                }
            }
            string url = WechatUrls.GetBaseTokenUrl();
            string content = HttpUtil.HttpGet(url);
            WxTokenObject tokenobj = JSON.parse<WxTokenObject>(content);
            tokenobj.expires_time = DateTime.Now.AddSeconds(tokenobj.expires_in);
            application.Set("token", tokenobj);
            return tokenobj.access_token;
        }
        /// <summary>
        /// 获得jsapi_ticket（有效期7200秒，开发者必须在自己的服务全局缓存jsapi_ticket）
        /// </summary>
        /// <returns></returns>
        public static string GetJSAPITicket()
        {
            HttpApplicationState application = HttpContext.Current.Application;
            object oticket = application.Get("jsapiticket");
            if (null != oticket)
            {
                WxJSAPITicketObject curticket = oticket as WxJSAPITicketObject;
                if (null != curticket && curticket.expires_time >= DateTime.Now)
                {
                    return curticket.ticket;
                }
            }
            string accesstoken = GetToken();
            string urljson = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accesstoken + "&type=jsapi";
            // {"errcode":0,"errmsg":"ok","ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA","expires_in":7200}
            string content = HttpUtil.HttpGet(urljson);
            WxJSAPITicketObject ticketobj = JSON.parse<WxJSAPITicketObject>(content);
            ticketobj.expires_time = DateTime.Now.AddSeconds(ticketobj.expires_in);
            application.Set("jsapiticket", ticketobj);
            return ticketobj.ticket;
        }
        /// <summary>
        /// 生成时间戳
        /// 从 1970 年 1 月 1 日 00：00：00 至今的秒数，即当前的时间，且最终需要转换为字符串形式
        /// </summary>
        /// <returns></returns>
        public static long GetTimestamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds);
        }
        /// <summary>
        /// 生成随机字符串
        /// </summary>
        /// <returns></returns>
        public static string GetNonceStr()
        {
            Random random = new Random();
            return MD5Util.GetMD5(random.Next(1000).ToString());
        }
        // http://www.cnblogs.com/ysyn/archive/2015/07/23/4665897.html
        public static string GetSignature(string ticket, string nonce, string timestamp,string url)
        {
            string tmpStr = string.Format("jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}",ticket,nonce,timestamp,url);
            string signature= FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1").ToLower();
            ResponseUtil.JsLog(tmpStr+"|signature="+signature);
            return signature;
        }
    }
}